//
//  SEGSpaceViewController.m
//  Uhomebk
//
//  Created by XXJ on 15/12/8.
//  Copyright © 2015年 com.segi. All rights reserved.
//

#import "SEGSpaceViewController.h"
@interface SEGSpaceViewController ()<UITableViewDataSource,UITableViewDelegate>

@end

@implementation SEGSpaceViewController

-(void)loadView
{
    
    CGSize size = [[UIScreen mainScreen] bounds].size;
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height-kNavigationBarAndStatusBarHeight)];
    self.view = mainView;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStylePlain];
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.backgroundColor = kColor_bg;
    _tableView.separatorColor=kColor_L2;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    _tableView.tableFooterView = [[UIView alloc] init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self showCustomNavigationBackButton];
    
    selectIndex = -1;
    
    dataArray = [[NSMutableArray alloc] init];
    
    saveDict = [[NSMutableDictionary alloc] init];
    
    if ([_typeStr isEqualToString:@"radio"]){
    } else {
        [self showCustomNavigationRightButtonWithTitle:@"确定" image:nil hightlightImage:nil];
    }
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)onNavigationLeftButtonClicked:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)onNavigationRightButtonClicked:(UIButton *)sender
{
    [self saveSelectedData];
}

/**
 多选才有确定按钮。选择数据要合并。
 */
- (void)onBtnFinishedAction:(UIButton *)sender {
    [self saveSelectedData];
}

/**
 保存选择好的数据
 */
- (void) saveSelectedData {
    if ([[saveDict allKeys] count]==0) {
        return;
    }
    NSArray *valueArr = [self getSelectedData];
    [self.fundelegate onRequestData:valueArr];
    [self.navigationController popViewControllerAnimated:YES];
}


/**
 获取选择好的数据
 */
-(NSArray *)getSelectedData {
    NSMutableArray *valueArr = [[NSMutableArray alloc] init];
    for (NSString *keyStr in [saveDict allKeys])
    {
        NSDictionary * dic = saveDict[keyStr];
        [valueArr addObject:dic];
    }
    return valueArr;
}

#pragma mark -
#pragma mark 加载数据
-(void)loadData
{
    //单选控件回填值逻辑 - 有缓存的回填值与系统给的默认值
    if ([_typeStr isEqualToString:@"radio"] ) {
        if ([[_tempDict valueForKey:@"initData"] length]==0) return;
        NSArray *strArray = [SEGUtils arrayWithJsonString:_tempDict[@"initData"]];
        [strArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            [dict setValue:@"No" forKey:@"Selected"];
            //有回填值
            if (_defaultStr.length > 0 ) {
                if ([_defaultStr isEqualToString:[SEGUtils ValueToString:dict[@"id"]]]) {
                    [dict setValue:@"Yes" forKey:@"Selected"];
                }
            }
            //没有回填值，取系统给的默认值
            else{
                if ([dict[@"isDefault"] intValue] == 1) {
                    [dict setValue:@"Yes" forKey:@"Selected"];
                }
            }
            if (dict) {
                [dataArray addObject:dict];
            }
        }];
        [_tableView reloadData];
    }
    if ([_typeStr isEqualToString:@"checkbox"]) {
        if ([[_tempDict valueForKey:@"initData"] length] ==0) return;
        NSArray *strArray = [SEGUtils arrayWithJsonString:_tempDict[@"initData"]];
        [strArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            [dict setValue:@"No" forKey:@"Selected"];
            //有回填值
            if (_defaultStr.length > 0 ) {
                NSArray *defautSeletedArr;
                if (![[SEGUtils arrayWithJsonString:_defaultStr] isKindOfClass:[NSArray class]]) {
                    defautSeletedArr = @[[SEGUtils arrayWithJsonString:_defaultStr]];
                } else {
                    defautSeletedArr = [SEGUtils arrayWithJsonString:_defaultStr];
                }
                for (NSString *str in defautSeletedArr) {
                    if ([str isEqualToString:[SEGUtils ValueToString:dict[@"id"]]]) {
                        [dict setValue:@"Yes" forKey:@"Selected"];
                    }
                }
            }
            //没有回填值，取系统给的默认值
            else{
                if ([dict[@"isDefault"] intValue] == 1) {
                    [dict setValue:@"Yes" forKey:@"Selected"];
                }
            }
            
            // 回填之前选中的数据状态
            [self.selectDataArray enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull selectSubDic, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *dictID = dict[@"id"];
                NSString *selectID = selectSubDic[@"id"];
                if ([dictID isKindOfClass:[NSString class]] && [selectID isKindOfClass:[NSString class]] && [dictID length] > 0 && [dictID isEqualToString:selectID]) {
                    [dict setValue:@"Yes" forKey:@"Selected"];
                    *stop = YES;
                }
            }];
            
            if (dict) {
                [dataArray addObject:dict];
            }
        }];
        [_tableView reloadData];
    }
}

#pragma mark -
#pragma mark TableView delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray count];
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    SEGBaseTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell==nil)
    {
        cell = [[SEGBaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
        
        //标题
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 200, 50)];
        titleLabel.tag = 100;
        [titleLabel setText:@""];
        [titleLabel setFont:kFont_16];
        [titleLabel setTextColor:kColor_1];
        titleLabel.numberOfLines=0;
        titleLabel.lineBreakMode=NSLineBreakByWordWrapping;
        [cell.contentView addSubview:titleLabel];
        
        //打勾
        UIImage *image = nil;
        if ([_typeStr isEqualToString:@"radio"])
        {
            image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select")];
        }
        else
        {
            image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select_nor")];
        }
        
        UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds)-image.size.width-20, (50-image.size.height)/2+2, image.size.width, image.size.height)];
        iconImageView.tag = 101;
        
        if ([_typeStr isEqualToString:@"radio"] )
        {
            //
        }
        else
        {
            [iconImageView setImage:image];
        }
        [cell.contentView addSubview:iconImageView];
    }
    
    UIImageView *aImageView = [cell.contentView viewWithTag:101];
    UILabel *titleLabel = [cell.contentView viewWithTag:100];
    
    NSDictionary *dict = [dataArray objectAtIndex:indexPath.row];
    
    NSString *name = [SEGUtils ValueToString:[dict valueForKey:@"value"]];
    if ([[dict valueForKey:@"organName"] length]>0) {
        name = [NSString stringWithFormat:@"%@ (%@)",[dict valueForKey:@"value"],[dict valueForKey:@"organName"]];
    }
    CGSize size = [name getAttributionHeightWithlineSpace:LINESPACE_6 font:kFont_16 width:LYScreenWidth()-60];
    CGFloat height= size.height>= 16 ? size.height : 16;
    [titleLabel extendAttributedString:name lineSpace:LINESPACE_6 font:kFont_16];
    titleLabel.frame=CGRectMake(20, 16, LYScreenWidth()-60, height+2);

    
    if ([[_tempDict valueForKey:@"widgetType"] isEqualToString:@"radio"]) //单选
    {
        if ([[dict valueForKey:@"Selected"] isEqualToString:@"Yes"])
        {
            [aImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select")]];
            [saveDict removeAllObjects];
            [saveDict setValue:dict forKey:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
        }
        else if (selectIndex==indexPath.row)
        {
            [aImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select")]];
            [saveDict removeAllObjects];
            [saveDict setValue:dict forKey:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
        }
        else
        {
            [aImageView setImage:nil];
        }
        
    }
    else if ([[_tempDict valueForKey:@"widgetType"] isEqualToString:@"checkbox"]) //多选
    {
        if ([[dict valueForKey:@"Selected"] isEqualToString:@"No"])
        {
            [aImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select_nor")]];
        }
        else
        {
            [aImageView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select")]];
            [saveDict setValue:dict forKey:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
        }
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSMutableDictionary *dic = [dataArray objectAtIndex:indexPath.row];
    
    if ([[_tempDict valueForKey:@"widgetType"] isEqualToString:@"radio"] ||[[_tempDict valueForKey:@"widgetType"] isEqualToString:@"enum"])  //单选
    {
        selectIndex = indexPath.row;
        [saveDict removeAllObjects];
        [saveDict setValue:dic forKey:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
        [self saveSelectedData];

    }
    else if([[_tempDict valueForKey:@"widgetType"] isEqualToString:@"checkbox"]) //多选
    {
        if ([[dic valueForKey:@"Selected"] isEqualToString:@"No"])
        {
            [saveDict setValue:dic forKey:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
            [dic setValue:@"Yes" forKey:@"Selected"];
        }
        else
        {
            [saveDict setValue:nil forKey:[NSString stringWithFormat:@"%d",(int)indexPath.row]];
            [dic setValue:@"No" forKey:@"Selected"];
        }
    }

    [_tableView reloadData];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary* dict = [dataArray objectAtIndex:indexPath.row];
    NSString *name=[NSString stringWithFormat:@"%@ (%@)",[dict valueForKey:@"value"],[dict valueForKey:@"organName"]];
    CGSize size = [name getAttributionHeightWithlineSpace:LINESPACE_6 font:kFont_16 width:LYScreenWidth()-60];
    CGFloat height= size.height>= 16 ? size.height : 16;
    return height+34;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

@end
